#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "configdialog.h"
#include <QApplication>
#include <QMessageBox>
#include <QInputDialog>
#include <QFileDialog>
#include <QCloseEvent>
#include <QSettings>
#include <QTimer>
#include <QSplitter>
#include <QTreeWidget>
#include <QTabWidget>
#include <QStatusBar>
#include <QLabel>
#include <QProgressBar>
#include <QSystemTrayIcon>
#include <QMenu>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QFormLayout>
#include <QDialogButtonBox>
#include <QFontComboBox>
#include <QSlider>
#include <QCheckBox>
#include <QComboBox>
#include <QSpinBox>
#include <QTextEdit>
#include <QPushButton>
#include <QGroupBox>
#include <QRadioButton>
#include <QToolButton>
#include <QHeaderView>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
    , m_sshManager(nullptr)
    , m_connectionManager(nullptr)
    , m_trayIcon(nullptr)
    , m_statusTimer(nullptr)
    , m_connectionTimer(nullptr)
    , m_settings(nullptr)
    , m_saveSettings(true)
    , m_confirmExit(true)
    , m_minimizeToTray(false)
    , m_startMinimized(false)
{
    ui->setupUi(this);

    // 初始化设置
    m_settings = new QSettings("SshTool", "SshTool", this);

    // 初始化管理器
    m_sshManager = new SshManager(this);
    m_connectionManager = new ConnectionManager(this);

    // 初始化定时器
    m_statusTimer = new QTimer(this);
    m_connectionTimer = new QTimer(this);

    // 创建UI组件
    createStatusBar();
    createSideBar();
    createTrayIcon();

    // 初始化连接
    initializeConnections();

    // 加载设置
    loadSettings();

    // 恢复窗口状态
    restoreWindowGeometry();

    // 设置窗口标题
    setWindowTitle("SshTool - SSH Terminal Client");
    setWindowIcon(QIcon(":/icons/app.png"));

    // 显示欢迎信息
    addSessionTab(createTerminalWidget(), "Welcome");
}

MainWindow::~MainWindow()
{
    saveSettings();

    // 清理资源
    if (m_sshManager) {
        m_sshManager->closeAllSessions();
    }

    delete ui;
}

bool MainWindow::createNewSession(const ConnectionManager::ConnectionProfile &profile)
{
    try {
        // 创建SSH会话
        SshManager::ConnectionConfig config;
        config.host = profile.host;
        config.port = profile.port;
        config.username = profile.username;
        config.password = profile.password;
        config.privateKeyPath = profile.privateKeyPath;
        config.timeout = 30;
        config.keepAlive = true;

        SshSession *session = m_sshManager->createSession(config);
        if (!session) {
            showError("Connection Error", "Failed to create SSH session");
            return false;
        }

        // 创建终端组件
        TerminalWidget *terminal = createTerminalWidget();
        terminal->setSshSession(session);

        // 添加标签页
        QString title = QString("%1@%2").arg(profile.username).arg(profile.host);
        addSessionTab(terminal, title);

        // 建立映射关系
        int tabIndex = ui->sessionTabs->count() - 1;
        m_tabSessionMap[tabIndex] = session->sessionId();
        m_terminalWidgets[session->sessionId()] = terminal;

        // 连接会话
        session->connectTo();

        return true;
    } catch (const std::exception &e) {
        showError("Connection Error", QString("Failed to create session: %1").arg(e.what()));
        return false;
    }
}

bool MainWindow::createQuickSession(const QString &host, int port, const QString &username, const QString &password)
{
    ConnectionManager::ConnectionProfile profile;
    profile.host = host;
    profile.port = port;
    profile.username = username;
    profile.password = password;
    profile.name = QString("%1@%2").arg(username).arg(host);

    return createNewSession(profile);
}

void MainWindow::closeCurrentSession()
{
    int currentIndex = ui->sessionTabs->currentIndex();
    if (currentIndex >= 0) {
        closeSessionTab(currentIndex);
    }
}

void MainWindow::closeAllSessions()
{
    while (ui->sessionTabs->count() > 0) {
        closeSessionTab(0);
    }
}

bool MainWindow::hasActiveSessions() const
{
    return m_sshManager && !m_sshManager->getActiveSessions().isEmpty();
}

int MainWindow::getSessionCount() const
{
    return ui->sessionTabs->count();
}

QString MainWindow::getCurrentSessionId() const
{
    int currentIndex = ui->sessionTabs->currentIndex();
    if (currentIndex >= 0) {
        return m_tabSessionMap.value(currentIndex);
    }
    return QString();
}

void MainWindow::closeSessionTab(int index)
{
    ui->sessionTabs->widget(index)->close();
}

void MainWindow::closeEvent(QCloseEvent *event)
{
    if (confirmExit()) {
        if (m_trayIcon && m_minimizeToTray) {
            hide();
            event->ignore();
        } else {
            saveSettings();
            event->accept();
        }
    } else {
        event->ignore();
    }
}

void MainWindow::showEvent(QShowEvent *event)
{
    QMainWindow::showEvent(event);
}

void MainWindow::hideEvent(QHideEvent *event)
{
    QMainWindow::hideEvent(event);
}

bool MainWindow::eventFilter(QObject *watched, QEvent *event)
{
    return QMainWindow::eventFilter(watched, event);
}

void MainWindow::newConnection()
{
    ConfigDialog dialog(this);
    dialog.setMode("create");

    if (dialog.exec() == QDialog::Accepted) {
        ConnectionManager::ConnectionProfile profile = dialog.getProfile();
        if (m_connectionManager->saveProfile(profile)) {
            createNewSession(profile);
            populateConnectionTree();
        }
    }
}

void MainWindow::quickConnect()
{
    bool ok;
    QString host = QInputDialog::getText(this, "Quick Connect", "Host:", QLineEdit::Normal, "", &ok);
    if (!ok || host.isEmpty()) return;

    QString username = QInputDialog::getText(this, "Quick Connect", "Username:", QLineEdit::Normal, "", &ok);
    if (!ok || username.isEmpty()) return;

    QString password = QInputDialog::getText(this, "Quick Connect", "Password:", QLineEdit::Password, "", &ok);
    if (!ok) return;

    createQuickSession(host, 22, username, password);
}

void MainWindow::reconnect()
{
    QString sessionId = getCurrentSessionId();
    if (!sessionId.isEmpty()) {
        // 重新连接逻辑
        updateStatus("Reconnecting...");
    }
}

void MainWindow::disconnectSession()
{
    closeCurrentSession();
}

void MainWindow::saveSession()
{
    // 保存会话逻辑
    updateStatus("Session saved");
}

void MainWindow::saveSessionAs()
{
    QString fileName = QFileDialog::getSaveFileName(this, "Save Session", "", "SshTool Session (*.sts)");
    if (!fileName.isEmpty()) {
        // 保存会话到文件
        updateStatus("Session saved to " + fileName);
    }
}

void MainWindow::loadSession()
{
    QString fileName = QFileDialog::getOpenFileName(this, "Load Session", "", "SshTool Session (*.sts)");
    if (!fileName.isEmpty()) {
        // 从文件加载会话
        updateStatus("Session loaded from " + fileName);
    }
}

void MainWindow::exportSettings()
{
    QString fileName = QFileDialog::getSaveFileName(this, "Export Settings", "", "SshTool Settings (*.json)");
    if (!fileName.isEmpty()) {
        if (m_connectionManager->exportProfiles(fileName)) {
            showInfo("Export Settings", "Settings exported successfully");
        }
    }
}

void MainWindow::importSettings()
{
    QString fileName = QFileDialog::getOpenFileName(this, "Import Settings", "", "SshTool Settings (*.json)");
    if (!fileName.isEmpty()) {
        if (m_connectionManager->importProfiles(fileName)) {
            showInfo("Import Settings", "Settings imported successfully");
            populateConnectionTree();
        }
    }
}

void MainWindow::exitApplication()
{
    if (confirmExit()) {
        QApplication::quit();
    }
}

void MainWindow::copy()
{
    int currentIndex = ui->sessionTabs->currentIndex();
    if (currentIndex >= 0) {
        TerminalWidget *terminal = qobject_cast<TerminalWidget*>(ui->sessionTabs->widget(currentIndex));
        if (terminal) {
            terminal->copy();
        }
    }
}

void MainWindow::paste()
{
    int currentIndex = ui->sessionTabs->currentIndex();
    if (currentIndex >= 0) {
        TerminalWidget *terminal = qobject_cast<TerminalWidget*>(ui->sessionTabs->widget(currentIndex));
        if (terminal) {
            terminal->paste();
        }
    }
}

void MainWindow::selectAll()
{
    int currentIndex = ui->sessionTabs->currentIndex();
    if (currentIndex >= 0) {
        TerminalWidget *terminal = qobject_cast<TerminalWidget*>(ui->sessionTabs->widget(currentIndex));
        if (terminal) {
            QTextCursor cursor = terminal->findChild<QPlainTextEdit*>()->textCursor();
            cursor.select(QTextCursor::Document);
            terminal->findChild<QPlainTextEdit*>()->setTextCursor(cursor);
        }
    }
}

void MainWindow::find()
{
    // 查找功能
    updateStatus("Find feature not implemented yet");
}

void MainWindow::clearScrollback()
{
    int currentIndex = ui->sessionTabs->currentIndex();
    if (currentIndex >= 0) {
        TerminalWidget *terminal = qobject_cast<TerminalWidget*>(ui->sessionTabs->widget(currentIndex));
        if (terminal) {
            terminal->clear();
        }
    }
}

void MainWindow::resetTerminal()
{
    int currentIndex = ui->sessionTabs->currentIndex();
    if (currentIndex >= 0) {
        TerminalWidget *terminal = qobject_cast<TerminalWidget*>(ui->sessionTabs->widget(currentIndex));
        if (terminal) {
            terminal->reset();
        }
    }
}

void MainWindow::toggleFullscreen()
{
    if (isFullScreen()) {
        showNormal();
    } else {
        showFullScreen();
    }
}

void MainWindow::toggleMenuBar()
{
    ui->menuBar->setVisible(!ui->menuBar->isVisible());
}

void MainWindow::toggleToolBar()
{
    ui->toolBar->setVisible(!ui->toolBar->isVisible());
}

void MainWindow::toggleStatusBar()
{
    ui->statusBar->setVisible(!ui->statusBar->isVisible());
}

void MainWindow::toggleSideBar()
{
    ui->connectionTree->setVisible(!ui->connectionTree->isVisible());
}

void MainWindow::zoomIn()
{
    int currentIndex = ui->sessionTabs->currentIndex();
    if (currentIndex >= 0) {
        TerminalWidget *terminal = qobject_cast<TerminalWidget*>(ui->sessionTabs->widget(currentIndex));
        if (terminal) {
            terminal->zoomIn();
        }
    }
}

void MainWindow::zoomOut()
{
    int currentIndex = ui->sessionTabs->currentIndex();
    if (currentIndex >= 0) {
        TerminalWidget *terminal = qobject_cast<TerminalWidget*>(ui->sessionTabs->widget(currentIndex));
        if (terminal) {
            terminal->zoomOut();
        }
    }
}

void MainWindow::zoomReset()
{
    int currentIndex = ui->sessionTabs->currentIndex();
    if (currentIndex >= 0) {
        TerminalWidget *terminal = qobject_cast<TerminalWidget*>(ui->sessionTabs->widget(currentIndex));
        if (terminal) {
            terminal->resetZoom();
        }
    }
}

void MainWindow::duplicateSession()
{
    QString sessionId = getCurrentSessionId();
    if (!sessionId.isEmpty()) {
        // 复制会话逻辑
        updateStatus("Duplicating session...");
    }
}

void MainWindow::renameSession()
{
    int currentIndex = ui->sessionTabs->currentIndex();
    if (currentIndex >= 0) {
        bool ok;
        QString newName = QInputDialog::getText(this, "Rename Session", "New name:", QLineEdit::Normal, ui->sessionTabs->tabText(currentIndex), &ok);
        if (ok && !newName.isEmpty()) {
            ui->sessionTabs->setTabText(currentIndex, newName);
        }
    }
}

void MainWindow::sessionProperties()
{
    QString sessionId = getCurrentSessionId();
    if (!sessionId.isEmpty()) {
        // 显示会话属性
        updateStatus("Session properties not implemented yet");
    }
}

void MainWindow::previousSession()
{
    int currentIndex = ui->sessionTabs->currentIndex();
    if (currentIndex > 0) {
        ui->sessionTabs->setCurrentIndex(currentIndex - 1);
    }
}

void MainWindow::nextSession()
{
    int currentIndex = ui->sessionTabs->currentIndex();
    if (currentIndex < ui->sessionTabs->count() - 1) {
        ui->sessionTabs->setCurrentIndex(currentIndex + 1);
    }
}

void MainWindow::moveSessionLeft()
{
    int currentIndex = ui->sessionTabs->currentIndex();
    if (currentIndex > 0) {
        QString text = ui->sessionTabs->tabText(currentIndex);
        QWidget *widget = ui->sessionTabs->widget(currentIndex);
        QIcon icon = ui->sessionTabs->tabIcon(currentIndex);

        ui->sessionTabs->removeTab(currentIndex);
        ui->sessionTabs->insertTab(currentIndex - 1, widget, icon, text);
        ui->sessionTabs->setCurrentIndex(currentIndex - 1);
    }
}

void MainWindow::moveSessionRight()
{
    int currentIndex = ui->sessionTabs->currentIndex();
    if (currentIndex < ui->sessionTabs->count() - 1) {
        QString text = ui->sessionTabs->tabText(currentIndex);
        QWidget *widget = ui->sessionTabs->widget(currentIndex);
        QIcon icon = ui->sessionTabs->tabIcon(currentIndex);

        ui->sessionTabs->removeTab(currentIndex);
        ui->sessionTabs->insertTab(currentIndex + 1, widget, icon, text);
        ui->sessionTabs->setCurrentIndex(currentIndex + 1);
    }
}

void MainWindow::openFileTransfer()
{
    // 打开文件传输窗口
    updateStatus("File transfer not implemented yet");
}

void MainWindow::uploadFile()
{
    QString fileName = QFileDialog::getOpenFileName(this, "Upload File");
    if (!fileName.isEmpty()) {
        // 上传文件逻辑
        updateStatus("Uploading file: " + fileName);
    }
}

void MainWindow::downloadFile()
{
    QString fileName = QFileDialog::getSaveFileName(this, "Download File");
    if (!fileName.isEmpty()) {
        // 下载文件逻辑
        updateStatus("Downloading to: " + fileName);
    }
}

void MainWindow::transferQueue()
{
    // 显示传输队列
    updateStatus("Transfer queue not implemented yet");
}

void MainWindow::transferHistory()
{
    // 显示传输历史
    updateStatus("Transfer history not implemented yet");
}

void MainWindow::keyManager()
{
    // 密钥管理器
    updateStatus("Key manager not implemented yet");
}

void MainWindow::sessionManager()
{
    // 会话管理器
    updateStatus("Session manager not implemented yet");
}

void MainWindow::connectionSettings()
{
    ConfigDialog dialog(this);
    dialog.setMode("edit");
    dialog.exec();
}

void MainWindow::preferences()
{
    // 偏好设置
    updateStatus("Preferences not implemented yet");
}

void MainWindow::generateKeyPair()
{
    // 生成密钥对
    updateStatus("Key pair generation not implemented yet");
}

void MainWindow::showAbout()
{
    QMessageBox::about(this, "About SshTool",
                      "SshTool v1.0.0\n\n"
                      "A powerful SSH terminal client built with Qt and libssh2.\n\n"
                      "Features:\n"
                      "• Multiple SSH sessions\n"
                      "• SFTP file transfer\n"
                      "• Port forwarding\n"
                      "• Session management\n"
                      "• ANSI terminal emulation\n\n"
                      "© 2024 SshTool Team");
}

void MainWindow::showHelp()
{
    QMessageBox::information(this, "Help",
                           "SshTool Help\n\n"
                           "Quick Start:\n"
                           "1. Click 'New Connection' or use Quick Connect\n"
                           "2. Enter connection details\n"
                           "3. Start using the terminal\n\n"
                           "Keyboard Shortcuts:\n"
                           "• Ctrl+N: New Connection\n"
                           "• Ctrl+Q: Quick Connect\n"
                           "• Ctrl+T: New Tab\n"
                           "• Ctrl+W: Close Tab\n"
                           "• Ctrl+Tab: Next Tab\n"
                           "• Ctrl+Shift+Tab: Previous Tab\n\n"
                           "For more help, visit the documentation.");
}

void MainWindow::showChangelog()
{
    QMessageBox::information(this, "Changelog",
                           "SshTool v1.0.0\n\n"
                           "New Features:\n"
                           "• Initial release\n"
                           "• Basic SSH terminal functionality\n"
                           "• Multiple session support\n"
                           "• Configuration management\n"
                           "• ANSI terminal emulation\n");
}

void MainWindow::checkForUpdates()
{
    updateStatus("Checking for updates...");
    // 检查更新逻辑
    updateStatus("You are using the latest version");
}

void MainWindow::onNewConnectionClicked()
{
    newConnection();
}

void MainWindow::onQuickConnectClicked()
{
    quickConnect();
}

void MainWindow::onDisconnectClicked()
{
    disconnectSession();
}

void MainWindow::onFileTransferClicked()
{
    openFileTransfer();
}

void MainWindow::onSettingsClicked()
{
    preferences();
}

void MainWindow::onTabChanged(int index)
{
    Q_UNUSED(index)
    updateConnectionStatus(getCurrentSessionId());
}

void MainWindow::onTabCloseRequested(int index)
{
    if (confirmCloseTab(index)) {
        removeSessionTab(index);
    }
}

void MainWindow::onTabMoved(int from, int to)
{
    // 更新标签页映射
    QString sessionId = m_tabSessionMap.take(from);
    m_tabSessionMap[to] = sessionId;
}

void MainWindow::onSessionConnected(const QString &sessionId)
{
    updateSessionTab(sessionId, generateSessionTitle(sessionId) + " ✓");
    updateConnectionStatus(sessionId);
    updateStatus("Connected to " + sessionId);
}

void MainWindow::onSessionDisconnected(const QString &sessionId)
{
    updateSessionTab(sessionId, generateSessionTitle(sessionId) + " ✗");
    updateConnectionStatus(sessionId);
    updateStatus("Disconnected from " + sessionId);
}

void MainWindow::onSessionError(const QString &sessionId, const QString &error)
{
    updateStatus("Error: " + error);
    showError("Session Error", error);
}

void MainWindow::onProfileCreated(const ConnectionManager::ConnectionProfile &profile)
{
    populateConnectionTree();
    updateStatus("Profile created: " + profile.name);
}

void MainWindow::onProfileUpdated(const ConnectionManager::ConnectionProfile &profile)
{
    populateConnectionTree();
    updateStatus("Profile updated: " + profile.name);
}

void MainWindow::onProfileDeleted(const QString &profileId)
{
    populateConnectionTree();
    updateStatus("Profile deleted");
}

void MainWindow::onTestConnectionRequested(const ConnectionManager::ConnectionProfile &profile)
{
    updateStatus("Testing connection to " + profile.host);
    // 测试连接逻辑
}

void MainWindow::onFileTransferProgress(const QString &transferId, qint64 transferred, qint64 total)
{
    int percentage = (total > 0) ? (transferred * 100 / total) : 0;
    updateProgress(percentage);
}

void MainWindow::onFileTransferFinished(const QString &transferId, bool success)
{
    if (success) {
        updateStatus("File transfer completed successfully");
    } else {
        updateStatus("File transfer failed");
    }
    updateProgress(0);
}

void MainWindow::onFileTransferError(const QString &transferId, const QString &error)
{
    updateStatus("File transfer error: " + error);
    showError("Transfer Error", error);
}

void MainWindow::onTrayIconActivated(QSystemTrayIcon::ActivationReason reason)
{
    switch (reason) {
    case QSystemTrayIcon::DoubleClick:
        setVisible(!isVisible());
        break;
    case QSystemTrayIcon::Trigger:
        if (isHidden()) {
            show();
            activateWindow();
        }
        break;
    default:
        break;
    }
}

void MainWindow::onTrayMenuRequested()
{
    // 托盘菜单逻辑
}

void MainWindow::onStatusTimer()
{
    updateTime();
}

void MainWindow::onConnectionTimer()
{
    // 检查连接状态
}

void MainWindow::createStatusBar()
{
    m_statusLabel = new QLabel("Ready");
    m_connectionLabel = new QLabel("No connection");
    m_encodingLabel = new QLabel("UTF-8");
    m_timeLabel = new QLabel();
    m_progressBar = new QProgressBar();
    m_progressBar->setVisible(false);
    m_progressBar->setMaximumWidth(150);

    ui->statusBar->addWidget(m_statusLabel, 1);
    ui->statusBar->addPermanentWidget(m_connectionLabel);
    ui->statusBar->addPermanentWidget(m_encodingLabel);
    ui->statusBar->addPermanentWidget(m_timeLabel);
    ui->statusBar->addPermanentWidget(m_progressBar);

    // 启动状态定时器
    connect(m_statusTimer, &QTimer::timeout, this, &MainWindow::onStatusTimer);
    m_statusTimer->start(1000);

    connect(m_connectionTimer, &QTimer::timeout, this, &MainWindow::onConnectionTimer);
    m_connectionTimer->start(5000);
}

void MainWindow::createSideBar()
{
    // 设置连接树
    ui->connectionTree->header()->hide();
    ui->connectionTree->setRootIsDecorated(true);
    ui->connectionTree->setContextMenuPolicy(Qt::CustomContextMenu);

    // 填充连接树
    populateConnectionTree();

    // 连接信号
    connect(ui->connectionTree, &QTreeWidget::itemDoubleClicked, this, [this](QTreeWidgetItem *item, int column) {
        Q_UNUSED(column)
        if (item && item->parent()) { // 只处理子项点击
            QString profileId = item->data(0, Qt::UserRole).toString();
            // 根据profileId连接
        }
    });
}

void MainWindow::createTrayIcon()
{
    if (QSystemTrayIcon::isSystemTrayAvailable()) {
        m_trayIcon = new QSystemTrayIcon(this);
        m_trayIcon->setIcon(QIcon(":/icons/app.png"));
        m_trayIcon->setToolTip("SshTool - SSH Terminal Client");

        QMenu *trayMenu = new QMenu(this);
        trayMenu->addAction("Show/Hide", this, [this]() { setVisible(!isVisible()); });
        trayMenu->addSeparator();
        trayMenu->addAction("New Connection", this, &MainWindow::newConnection);
        trayMenu->addAction("Quick Connect", this, &MainWindow::quickConnect);
        trayMenu->addSeparator();
        trayMenu->addAction("Exit", this, &MainWindow::exitApplication);

        m_trayIcon->setContextMenu(trayMenu);

        connect(m_trayIcon, &QSystemTrayIcon::activated, this, &MainWindow::onTrayIconActivated);

        m_trayIcon->show();
    }
}

void MainWindow::initializeConnections()
{
    // 连接菜单动作
    connect(ui->newConnectionAction, &QAction::triggered, this, &MainWindow::newConnection);
    connect(ui->quickConnectAction, &QAction::triggered, this, &MainWindow::quickConnect);
    connect(ui->reconnectAction, &QAction::triggered, this, &MainWindow::reconnect);
    connect(ui->disconnectAction, &QAction::triggered, this, &MainWindow::disconnectSession);
    connect(ui->exitAction, &QAction::triggered, this, &MainWindow::exitApplication);

    // 编辑菜单
    connect(ui->copyAction, &QAction::triggered, this, &MainWindow::copy);
    connect(ui->pasteAction, &QAction::triggered, this, &MainWindow::paste);
    connect(ui->selectAllAction, &QAction::triggered, this, &MainWindow::selectAll);

    // 标签页信号
    connect(ui->sessionTabs, &QTabWidget::currentChanged, this, &MainWindow::onTabChanged);
    connect(ui->sessionTabs, &QTabWidget::tabCloseRequested, this, &MainWindow::onTabCloseRequested);
    connect(ui->sessionTabs, &QTabWidget::tabBarClicked, this, [this](int index) {
        Q_UNUSED(index);
        // tabMoved signal has different signature, handle tab move separately if needed
    });

    // 连接管理器信号
    connect(m_connectionManager, &ConnectionManager::profileAdded, this, &MainWindow::onProfileCreated);
    connect(m_connectionManager, &ConnectionManager::profileUpdated, this, &MainWindow::onProfileUpdated);
    connect(m_connectionManager, &ConnectionManager::profileDeleted, this, &MainWindow::onProfileDeleted);
}

void MainWindow::loadSettings()
{
    m_settings->beginGroup("MainWindow");
    m_saveSettings = m_settings->value("saveSettings", true).toBool();
    m_confirmExit = m_settings->value("confirmExit", true).toBool();
    m_minimizeToTray = m_settings->value("minimizeToTray", false).toBool();
    m_startMinimized = m_settings->value("startMinimized", false).toBool();
    m_settings->endGroup();

    // 加载连接管理器设置
    m_connectionManager->loadSettings();
}

void MainWindow::saveSettings()
{
    if (m_saveSettings) {
        m_settings->beginGroup("MainWindow");
        m_settings->setValue("saveSettings", m_saveSettings);
        m_settings->setValue("confirmExit", m_confirmExit);
        m_settings->setValue("minimizeToTray", m_minimizeToTray);
        m_settings->setValue("startMinimized", m_startMinimized);
        m_settings->endGroup();

        // 保存连接管理器设置
        m_connectionManager->saveSettings();
    }
}

void MainWindow::restoreSessionState()
{
    // 恢复会话状态
    // 这里可以实现自动重新连接上次打开的会话
}

TerminalWidget *MainWindow::createTerminalWidget()
{
    TerminalWidget *terminal = new TerminalWidget(this);
    return terminal;
}

SftpManager *MainWindow::createSftpManager(SshSession *session)
{
    SftpManager *sftpManager = new SftpManager(session, this);
    return sftpManager;
}

void MainWindow::addSessionTab(TerminalWidget *terminal, const QString &title)
{
    int index = ui->sessionTabs->addTab(terminal, title);
    ui->sessionTabs->setTabIcon(index, getSessionIcon(false));
    ui->sessionTabs->setCurrentIndex(index);
}

void MainWindow::removeSessionTab(int index)
{
    if (index >= 0 && index < ui->sessionTabs->count()) {
        QWidget *widget = ui->sessionTabs->widget(index);
        QString sessionId = m_tabSessionMap.take(index);

        // 清理映射关系
        m_terminalWidgets.remove(sessionId);
        m_sftpManagers.remove(sessionId);

        // 移除标签页
        ui->sessionTabs->removeTab(index);

        // 删除组件
        widget->deleteLater();

        // 如果没有标签页了，创建一个欢迎页面
        if (ui->sessionTabs->count() == 0) {
            addSessionTab(createTerminalWidget(), "Welcome");
        }
    }
}

void MainWindow::updateSessionTab(const QString &sessionId, const QString &title)
{
    // 更新标签页标题
    for (int i = 0; i < ui->sessionTabs->count(); i++) {
        if (m_tabSessionMap.value(i) == sessionId) {
            ui->sessionTabs->setTabText(i, title);
            break;
        }
    }
}

void MainWindow::updateTabTitles()
{
    // 更新所有标签页标题
    for (int i = 0; i < ui->sessionTabs->count(); i++) {
        QString sessionId = m_tabSessionMap.value(i);
        QString title = generateSessionTitle(sessionId);
        ui->sessionTabs->setTabText(i, title);
    }
}

void MainWindow::cleanupSession(const QString &sessionId)
{
    // 清理会话相关资源
    m_terminalWidgets.remove(sessionId);
    m_sftpManagers.remove(sessionId);
}

void MainWindow::populateConnectionTree()
{
    ui->connectionTree->clear();

    // 获取所有配置文件
    QList<ConnectionManager::ConnectionProfile> profiles = m_connectionManager->getAllProfiles();

    // 按组分组
    QMap<QString, QList<ConnectionManager::ConnectionProfile>> groupedProfiles;
    for (const ConnectionManager::ConnectionProfile &profile : profiles) {
        QString group = profile.group.isEmpty() ? "Ungrouped" : profile.group;
        groupedProfiles[group].append(profile);
    }

    // 填充树
    for (const QString &group : groupedProfiles.keys()) {
        QTreeWidgetItem *groupItem = new QTreeWidgetItem(ui->connectionTree, QStringList(group));
        groupItem->setExpanded(true);

        for (const ConnectionManager::ConnectionProfile &profile : groupedProfiles[group]) {
            QTreeWidgetItem *profileItem = new QTreeWidgetItem(groupItem, QStringList(profile.name));
            profileItem->setData(0, Qt::UserRole, profile.id);
            profileItem->setIcon(0, getSessionIcon(false));
        }
    }
}

void MainWindow::addProfileToTree(const ConnectionManager::ConnectionProfile &profile)
{
    populateConnectionTree();
}

void MainWindow::removeProfileFromTree(const QString &profileId)
{
    populateConnectionTree();
}

void MainWindow::updateProfileInTree(const ConnectionManager::ConnectionProfile &profile)
{
    populateConnectionTree();
}

void MainWindow::updateTransferList()
{
    // 更新传输列表
}

void MainWindow::addTransferToList(const SftpManager::FileTransferInfo &transfer)
{
    // 添加传输到列表
}

void MainWindow::removeTransferFromList(const QString &transferId)
{
    // 从列表中移除传输
}

void MainWindow::updateStatus(const QString &message)
{
    m_statusLabel->setText(message);
}

void MainWindow::updateConnectionStatus(const QString &sessionId)
{
    if (sessionId.isEmpty()) {
        m_connectionLabel->setText("No connection");
    } else {
        SshSession *session = m_sshManager->getSession(sessionId);
        if (session) {
            QString status = QString("%1@%2:%3")
                               .arg(session->username())
                               .arg(session->host())
                               .arg(session->port());
            m_connectionLabel->setText(status);
        }
    }
}

void MainWindow::updateEncodingStatus()
{
    m_encodingLabel->setText("UTF-8");
}

void MainWindow::updateProgress(int value, int maximum)
{
    if (value == 0) {
        m_progressBar->setVisible(false);
        m_progressBar->setValue(0);
    } else {
        m_progressBar->setVisible(true);
        m_progressBar->setMaximum(maximum);
        m_progressBar->setValue(value);
    }
}

void MainWindow::updateTime()
{
    m_timeLabel->setText(QDateTime::currentDateTime().toString("hh:mm:ss"));
}

bool MainWindow::confirmExit()
{
    if (m_confirmExit && hasActiveSessions()) {
        QMessageBox::StandardButton reply = QMessageBox::question(
            this, "Confirm Exit",
            "You have active SSH sessions. Are you sure you want to exit?",
            QMessageBox::Yes | QMessageBox::No
        );
        return reply == QMessageBox::Yes;
    }
    return true;
}

bool MainWindow::confirmDisconnect(const QString &sessionId)
{
    QMessageBox::StandardButton reply = QMessageBox::question(
        this, "Confirm Disconnect",
        "Are you sure you want to disconnect from this session?",
        QMessageBox::Yes | QMessageBox::No
    );
    return reply == QMessageBox::Yes;
}

bool MainWindow::confirmCloseTab(int index)
{
    if (index >= 0 && index < ui->sessionTabs->count()) {
        QWidget *widget = ui->sessionTabs->widget(index);
        TerminalWidget *terminal = qobject_cast<TerminalWidget*>(widget);
        if (terminal && terminal->hasSession()) {
            QMessageBox::StandardButton reply = QMessageBox::question(
                this, "Confirm Close",
                "This tab has an active SSH session. Are you sure you want to close it?",
                QMessageBox::Yes | QMessageBox::No
            );
            return reply == QMessageBox::Yes;
        }
    }
    return true;
}

void MainWindow::showError(const QString &title, const QString &message)
{
    QMessageBox::critical(this, title, message);
}

void MainWindow::showInfo(const QString &title, const QString &message)
{
    QMessageBox::information(this, title, message);
}

void MainWindow::showWarning(const QString &title, const QString &message)
{
    QMessageBox::warning(this, title, message);
}

QString MainWindow::generateSessionTitle(const QString &sessionId) const
{
    SshSession *session = m_sshManager->getSession(sessionId);
    if (session) {
        return QString("%1@%2").arg(session->username()).arg(session->host());
    }
    return "Unknown";
}

QIcon MainWindow::getSessionIcon(bool connected) const
{
    // 返回连接状态图标
    return QIcon(connected ? ":/icons/connected.png" : ":/icons/disconnected.png");
}

QString MainWindow::formatDuration(qint64 seconds) const
{
    if (seconds < 60) {
        return QString("%1s").arg(seconds);
    } else if (seconds < 3600) {
        return QString("%1m %2s").arg(seconds / 60).arg(seconds % 60);
    } else {
        return QString("%1h %2m %3s").arg(seconds / 3600).arg((seconds % 3600) / 60).arg(seconds % 60);
    }
}

QString MainWindow::formatSize(qint64 bytes) const
{
    if (bytes < 1024) {
        return QString("%1 B").arg(bytes);
    } else if (bytes < 1024 * 1024) {
        return QString("%1 KB").arg(bytes / 1024);
    } else if (bytes < 1024 * 1024 * 1024) {
        return QString("%1 MB").arg(bytes / (1024 * 1024));
    } else {
        return QString("%1 GB").arg(bytes / (1024 * 1024 * 1024));
    }
}

void MainWindow::centerWindow()
{
    // 居中窗口
    QRect screenGeometry = QApplication::desktop()->screenGeometry();
    int x = (screenGeometry.width() - width()) / 2;
    int y = (screenGeometry.height() - height()) / 2;
    move(x, y);
}

void MainWindow::saveWindowGeometry()
{
    m_settings->beginGroup("MainWindow");
    m_settings->setValue("geometry", saveGeometry());
    m_settings->setValue("maximized", isMaximized());
    m_settings->setValue("fullScreen", isFullScreen());
    m_settings->endGroup();
}

void MainWindow::restoreWindowGeometry()
{
    m_settings->beginGroup("MainWindow");
    restoreGeometry(m_settings->value("geometry").toByteArray());
    if (m_settings->value("maximized", false).toBool()) {
        showMaximized();
    }
    if (m_settings->value("fullScreen", false).toBool()) {
        showFullScreen();
    }
    m_settings->endGroup();
}

bool MainWindow::showQuickConnectDialog()
{
    // 显示快速连接对话框
    return true;
}

bool MainWindow::showConnectionDialog(ConnectionManager::ConnectionProfile &profile)
{
    // 显示连接对话框
    return true;
}

bool MainWindow::importProfilesFromFile(const QString &filePath)
{
    return m_connectionManager->importProfiles(filePath);
}

bool MainWindow::exportProfilesToFile(const QString &filePath)
{
    return m_connectionManager->exportProfiles(filePath);
}
